package com.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.entity.Article;
import com.entity.Asks;
import com.entity.Cart;
import com.entity.Cate;
import com.entity.Complains;
import com.entity.Fav;
import com.entity.Goods;
import com.entity.Hist;
import com.entity.Items;
import com.entity.Orders;
import com.entity.Seller;
import com.entity.Topic;
import com.entity.Users;
import com.github.pagehelper.Page;
import com.service.ArticleService;
import com.service.AsksService;
import com.service.CartService;
import com.service.CateService;
import com.service.ComplainsService;
import com.service.FavService;
import com.service.GoodsService;
import com.service.HistService;
import com.service.OrdersService;
import com.service.RecommendService;
import com.service.SellerService;
import com.service.TopicService;
import com.service.UsersService;
import com.util.VeDate;

@RestController // 定义为控制器 返回JSON类型数据
@RequestMapping(value = "/index", produces = "application/json; charset=utf-8") // 设置请求路径
@CrossOrigin // 允许跨域访问其资源
//
public class IndexController extends BaseController {

	// @Autowired的作用是自动注入依赖的ServiceBean
	@Autowired
	private AsksService asksService;
	@Autowired
	private SellerService sellerService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private ArticleService articleService;
	@Autowired
	private CateService cateService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private CartService cartService;
	@Autowired
	private HistService histService;
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private TopicService topicService;
	@Autowired
	private ComplainsService complainsService;
	@Autowired
	private FavService favService;
	@Autowired
	private RecommendService recommendService;

	// TODO Auto-generated method stub

	// 预处理 获取基础参数
	@GetMapping(value = "front.action")
	public Map<String, Object> front() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Cate> cateList = this.cateService.getAllCate();
		map.put("cateList", cateList);
		List<Goods> hotList = this.goodsService.getGoodsByHot();

		//视图调用
		//List<Goods> hotList = this.goodsService.getGoodsByHotView();

		map.put("hotList", hotList);
		return map;
	}

	@RequestMapping(value = "query.action")
	public Map<String, Object> query(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit,
									 String name) {
		Map<String, Object> map = new HashMap<String, Object>();
		Page<Goods> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
		Goods goods = new Goods();
		goods.setGoodsname(name);
		List<Goods> goodsList = this.goodsService.getGoodsByLike(goods);
		// 返回的map中定义数据格式
		map.put("count", pager.getTotal());
		map.put("total", goodsList.size());
		map.put("data", goodsList);
		map.put("code", 0);
		map.put("msg", "");
		map.put("page", page);
		map.put("limit", limit);
		return map;
	}

	// 前台首页
	@GetMapping(value = "index.action")
	public Map<String, Object> index() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Cate> cateList = this.cateService.getCateFront();
		List<Cate> frontList = new ArrayList<Cate>();
		for (Cate cate : cateList) {
			List<Goods> goodsList = this.goodsService.getGoodsByCate(cate.getCateid());
			cate.setGoodsList(goodsList);
			frontList.add(cate);
		}
		map.put("frontList", frontList);
		return map;
	}

	// 新闻公告
	@GetMapping(value = "article.action")
	public Map<String, Object> article(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer limit) {
		Map<String, Object> map = new HashMap<String, Object>();
		Page<Article> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
		List<Article> list = this.articleService.getAllArticle();
		// 返回的map中定义数据格式
		map.put("count", pager.getTotal());
		map.put("total", list.size());
		map.put("data", list);
		map.put("code", 0);
		map.put("msg", "");
		map.put("page", page);
		map.put("limit", limit);
		return map;
	}

	// 公告详情
	@GetMapping(value = "read.action")
	public Map<String, Object> read(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Article article = this.articleService.getArticleById(id);
		article.setHits("" + (Integer.parseInt(article.getHits()) + 1));
		this.articleService.updateArticle(article);
		map.put("article", article);
		return map;
	}

	// 用户登录
	@PostMapping(value = "login.action")
	public Map<String, Object> login(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr);
		String username = obj.getString("username");
		String password = obj.getString("password");
		Users usersEntity = new Users();
		usersEntity.setUsername(username);
		List<Users> userslist = this.usersService.getUsersByCond(usersEntity);
		if (userslist.size() == 0) {
			map.put("success", false);
			map.put("message", "用户名不存在");
		} else {
			Users users = userslist.get(0);
			if (password.equals(users.getPassword())) {
				map.put("success", true);
				map.put("message", "登录成功");
				map.put("userid", users.getUsersid());
				map.put("username", users.getUsername());
				map.put("realname", users.getRealname());
			} else {
				map.put("success", false);
				map.put("message", "密码错误");
			}
		}
		return map;
	}

	@PostMapping(value = "slogin.action")
	public Map<String, Object> slogin(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr);
		String username = obj.getString("username");
		String password = obj.getString("password");
		Seller sellerEntity = new Seller();
		sellerEntity.setUsername(username);
		List<Seller> sellerlist = this.sellerService.getSellerByCond(sellerEntity);
		if (sellerlist.size() == 0) {
			map.put("success", false);
			map.put("message", "商户不存在");
		} else {
			Seller seller = sellerlist.get(0);
			if ("待审核".equals(seller.getStatus())) {
				map.put("success", false);
				map.put("message", "商户待审核");
			} else if (password.equals(seller.getPassword())) {
				map.put("success", true);
				map.put("message", "登录成功");
				map.put("sellerid", seller.getSellerid());
				map.put("username", seller.getUsername());
				map.put("sellername", seller.getSellername());
			} else {
				map.put("success", false);
				map.put("message", "密码错误");
			}
		}
		return map;
	}

	// 忘记密码1
	@PostMapping(value = "forget.action")
	public Map<String, Object> forget(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr);
		String username = obj.getString("username");
		Users usersEntity = new Users();
		usersEntity.setUsername(username);
		List<Users> userslist = this.usersService.getUsersByCond(usersEntity);
		if (userslist.size() == 0) {
			map.put("success", false);
			map.put("message", "用户名不存在");
		} else {
			map.put("success", true);
			map.put("message", "验证成功");
			map.put("users", userslist.get(0));
		}
		return map;
	}

	// 获取提示问题
	@GetMapping(value = "asks.action")
	public List<Asks> asks() {
		return this.asksService.getAllAsks();
	}

	// 用户注册
	@PostMapping(value = "register.action")
	public Map<String, Object> register(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
		Users users = new Users();
		users.setUsername(obj.getString("username"));
		users.setPassword(obj.getString("password"));
		users.setSex(obj.getString("sex"));
		users.setBirthday(obj.getString("birthday"));
		users.setContact(obj.getString("contact"));
		users.setRealname(obj.getString("realname"));
		users.setAsksid(obj.getString("asksid"));
		users.setAnswer(obj.getString("answer"));
		users.setRegdate(VeDate.getStringDateShort());
		int num = this.usersService.insertUsers(users);
		if (num > 0) {
			map.put("success", true);
			map.put("code", num);
			map.put("message", "注册成功");
		} else {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "注册失败");
		}
		return map;
	}

	@PostMapping(value = "sregister.action")
	public Map<String, Object> sregister(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
		Seller seller = new Seller();
		seller.setUsername(obj.getString("username")); // 为用户名赋值
		seller.setPassword(obj.getString("password")); // 为密码赋值
		seller.setSellername(obj.getString("sellername")); // 为店铺名称赋值
		seller.setContact(obj.getString("contact")); // 为联系方式赋值
		seller.setAddress(obj.getString("address")); // 为联系地址赋值
		seller.setStatus("待审核"); // 为状态赋值
		seller.setRegdate(VeDate.getStringDateShort()); // 为注册日期赋值
		int num = this.sellerService.insertSeller(seller);
		if (num > 0) {
			map.put("success", true);
			map.put("code", num);
			map.put("message", "注册成功");
		} else {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "注册失败");
		}
		return map;
	}

	// 修改密码
	@PostMapping(value = "editpwd.action")
	public Map<String, Object> editpwd(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
		String userid = obj.getString("userid");
		String password = obj.getString("password");
		String repassword = obj.getString("repassword");
		int num = 0;
		Users users = this.usersService.getUsersById(userid);
		if (password.equals(users.getPassword())) {
			users.setPassword(repassword);
			num = this.usersService.updateUsers(users);
			if (num > 0) {
				map.put("success", true);
				map.put("code", num);
				map.put("message", "修改成功");
			} else {
				map.put("success", false);
				map.put("code", num);
				map.put("message", "修改失败");
			}
		} else {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "旧密码错误");
		}
		return map;
	}

	@PostMapping(value = "repassword.action")
	public Map<String, Object> repassword(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
		String userid = obj.getString("userid");
		String repassword = obj.getString("repassword");
		System.out.println(jsonStr);
		int num = 0;
		Users users = this.usersService.getUsersById(userid);
		users.setPassword(repassword);
		num = this.usersService.updateUsers(users);
		if (num > 0) {
			map.put("success", true);
			map.put("code", num);
			map.put("message", "修改成功");
		} else {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "修改失败");
		}
		return map;
	}

	// 查看个人信息
	@GetMapping(value = "userinfo.action")
	public Map<String, Object> userinfo(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Users users = this.usersService.getUsersById(id);
		map.put("users", users);
		return map;
	}

	// 修改个人信息
	@PostMapping(value = "personal.action")
	public Map<String, Object> personal(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
		Users users = this.usersService.getUsersById(obj.getString("usersid"));
		users.setUsername(obj.getString("username"));
		users.setSex(obj.getString("sex"));
		users.setBirthday(obj.getString("birthday"));
		users.setContact(obj.getString("contact"));
		users.setRealname(obj.getString("realname"));
		int num = this.usersService.updateUsers(users);
		if (num > 0) {
			map.put("success", true);
			map.put("code", num);
			map.put("message", "修改成功");
		} else {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "修改失败");
		}
		return map;
	}

	// 查看购物车
	@GetMapping(value = "cart.action")
	public Map<String, Object> cart(String userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		Cart cart = new Cart();
		cart.setUsersid(userid);
		List<Cart> cartList = this.cartService.getCartByCond(cart);
		map.put("cartList", cartList);
		map.put("num", cartList.size());
		return map;
	}

	// 删除购物车中的商品
	@RequestMapping(value = "deletecart.action")
	public Map<String, Object> deletecart(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		int num = this.cartService.deleteCart(id);
		if (num > 0) {
			map.put("success", true);
			map.put("code", num);
			map.put("message", "删除成功");
		} else {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "删除失败");
		}
		return map;
	}

	// 查看订单
	@RequestMapping(value = "showOrders.action")
	public Map<String, Object> showOrders(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit,
			String userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		Orders orders = new Orders();
		orders.setUsersid(userid);
		Page<Orders> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
		List<Orders> list = this.ordersService.getOrdersByCond(orders);
		// 返回的map中定义数据格式
		map.put("count", pager.getTotal());
		map.put("total", list.size());
		map.put("data", list);
		map.put("code", 0);
		map.put("msg", "");
		map.put("page", page);
		map.put("limit", limit);
		return map;
	}

	// 添加商品到购物车
	@PostMapping(value = "addcart.action")
	public Map<String, Object> addcart(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
		Cart cart = new Cart();
		cart.setUsersid(obj.getString("userid"));
		cart.setAddtime(VeDate.getStringDateShort());
		cart.setGoodsid(obj.getString("goodsid"));
		cart.setNum(obj.getString("num"));
		cart.setPrice(obj.getString("price"));
		int num = this.cartService.insertCart(cart);
		if (num > 0) {
			map.put("success", true);
			map.put("code", num);
			map.put("message", "成功");
		} else {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "失败");
		}
		return map;
	}

	// 购物结算
	@RequestMapping(value = "checkout.action", method = RequestMethod.POST)
	public Map<String, Object> checkout(@RequestBody String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
		Cart cart1 = new Cart();
		cart1.setUsersid(obj.getString("userid"));
		List<Cart> cartList = this.cartService.getCartByCond(cart1);
		int num = 0;
		if (cartList.size() == 0) {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "失败");
		} else {
			double total = 0;
			for (Cart cart : cartList) {
				// 获取一个1000-9999的随机数 防止同时提交
				String ordercode = "PD" + VeDate.getStringDatex();
				Orders orders = new Orders();
				orders.setAddress(obj.getString("address"));
				orders.setAddtime(VeDate.getStringDateShort());
				orders.setContact(obj.getString("contact"));
				orders.setOrdercode(ordercode);
				orders.setReceiver(obj.getString("receiver"));
				orders.setStatus("未付款");
				orders.setTotal("" + VeDate.getDouble(total));
				orders.setUsersid(obj.getString("userid"));
				orders.setGoodsid(cart.getGoodsid());
				orders.setPrice(cart.getPrice());
				orders.setNum(cart.getNum());
				orders.setTotal(""
						+ VeDate.getDouble(Double.parseDouble("" + Double.parseDouble(cart.getNum()) * Double.parseDouble(cart.getPrice()))));
				num += this.ordersService.insertOrders(orders);
				Goods goods = this.goodsService.getGoodsById(cart.getGoodsid());
				goods.setSellnum("" + (Integer.parseInt(goods.getSellnum()) + Integer.parseInt(cart.getNum())));
				this.goodsService.updateGoods(goods);
				total += Double.parseDouble(cart.getPrice()) * Double.parseDouble(cart.getNum());
				this.cartService.deleteCart(cart.getCartid());
			}
		}
		if (num > 0) {
			map.put("success", true);
			map.put("code", num);
			map.put("message", "成功");
		} else {
			map.put("success", false);
			map.put("code", num);
			map.put("message", "失败");
		}
		return map;
	}

	//
	@RequestMapping(value = "prePay.action")
	public Map<String, Object> prePay(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Orders orders = this.ordersService.getOrdersById(id);
		map.put("orders", orders);
		return map;
	}


	// 我的意见反馈信息
	@RequestMapping(value = "myComplains.action")
	public Map<String, Object> myComplains(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit,
			String userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		Complains complains = new Complains();
		complains.setUsersid(userid);
		// 定义当前页和分页条数
		Page<Complains> pager = com.github.pagehelper.PageHelper.startPage(page, limit);
		List<Complains> complainsList = this.complainsService.getComplainsByCond(complains);
		// 返回的map中定义数据格式
		map.put("count", pager.getTotal());
		map.put("total", complainsList.size());
		map.put("data", complainsList);
		map.put("code", 0);
		map.put("msg", "");
		map.put("page", page);
		map.put("limit", limit);
		return map;
	}

	@RequestMapping(value = "cate.action")
	public Map<String, Object> cate(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit,
			String id) {
		System.out.println("cateid  ==>  " + id);
		Map<String, Object> map = new HashMap<String, Object>();
		Cate cate = this.cateService.getCateById(id);
		Goods goods = new Goods();
		goods.setCateid(id);
		Page<Goods> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
		List<Goods> goodsList = this.goodsService.getGoodsByCond(goods);
		// 返回的map中定义数据格式
		map.put("count", pager.getTotal());
		map.put("total", goodsList.size());
		map.put("data", goodsList);
		map.put("code", 0);
		map.put("msg", "");
		map.put("page", page);
		map.put("limit", limit);
		map.put("cate", cate);
		return map;
	}

	@RequestMapping(value = "all.action")
	public Map<String, Object> all(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit) {
		Map<String, Object> map = new HashMap<String, Object>();
		Page<Goods> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
		List<Goods> goodsList = this.goodsService.getAllGoods();
		// 返回的map中定义数据格式
		map.put("count", pager.getTotal());
		map.put("total", goodsList.size());
		map.put("data", goodsList);
		map.put("code", 0);
		map.put("msg", "");
		map.put("page", page);
		map.put("limit", limit);
		return map;
	}


	@RequestMapping(value = "detail.action")
	public Map<String, Object> detail(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Goods goods = this.goodsService.getGoodsById(id);
		goods.setHits("" + (Integer.parseInt(goods.getHits()) + 1));
		this.goodsService.updateGoods(goods);
		map.put("goods", goods);
		Topic topic = new Topic();
		topic.setGoodsid(id);
		List<Topic> topicList = this.topicService.getTopicByCond(topic);
		map.put("topicList", topicList);
		return map;
	}

	@RequestMapping(value = "userdetail.action")
	public Map<String, Object> userdetail(String id, String userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		Goods goods = this.goodsService.getGoodsById(id);
		goods.setHits("" + (Integer.parseInt(goods.getHits()) + 1));
		this.goodsService.updateGoods(goods);
		map.put("goods", goods);
		Topic topic = new Topic();
		topic.setGoodsid(id);
		List<Topic> topicList = this.topicService.getTopicByCond(topic);
		map.put("topicList", topicList);
		System.out.println(" userid ====> " + userid);
		Hist hist = new Hist();
		hist.setUsersid(userid);
		hist.setGoodsid(id);
		List<Hist> histList = this.histService.getHistByCond(hist);
		if (histList.size() == 0) {
			hist.setNum("1");
			this.histService.insertHist(hist);
		}
		return map;
	}

	@RequestMapping(value = "preTopic.action")
	public Map<String, Object> preTopic(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Orders orders = this.ordersService.getOrdersById(id);
		map.put("orders", orders);
		String ordercode = orders.getOrdercode();
		List<Items> itemsList = new ArrayList<Items>();
		Items items = new Items();
		items.setGoodsid(orders.getGoodsid());
		items.setGoodsname(orders.getGoodsname());
		items.setOrdercode(ordercode);
		itemsList.add(items);
		map.put("detailsList", itemsList);
		return map;
	}



	// 我的收藏
	@GetMapping(value = "myfav.action")
	public Map<String, Object> myfav(String userid, @RequestParam(defaultValue = "1") Integer page,
			@RequestParam(defaultValue = "10") Integer limit) {
		Map<String, Object> map = new HashMap<String, Object>();
		Page<Fav> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
		Fav fav = new Fav();
		fav.setUsersid(userid);
		List<Fav> list = this.favService.getFavByCond(fav);
		// 返回的map中定义数据格式
		map.put("count", pager.getTotal());
		map.put("total", list.size());
		map.put("data", list);
		map.put("code", 0);
		map.put("msg", "");
		map.put("page", page);
		map.put("limit", limit);
		return map;
	}


	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/*", method = RequestMethod.OPTIONS)
	public ResponseEntity handleOptions() {
		return (ResponseEntity) ResponseEntity.noContent();
	}

	// TODO Auto-generated method stub
}
